import React, {useRef, useEffect} from 'react';
import echarts from 'echarts';
export default function lineMap(props) {
  const barNode = useRef(null);
  let myecharts = null;
  useEffect(() => {
    getLine();
    window.addEventListener('resize', () => {
      myecharts && myecharts.resize();
    });  
  },[props.data])
  useEffect(() => {
    return () => {
      myecharts && myecharts.dispose();
      window.removeEventListener('resize', ()=> {myecharts && myecharts.resize();})
    }
  },[])
  function getLine() {
    const xlist = (props.data.length && props.data[0].value.map(item => item.index)) || [];
    const serviesData = (props.data.length && props.data.map(it => {
      const lists = it.value.map(item => item.requests);
      const obj = {
        name: `${it.name}`,
        type: it.type,
        data: lists
      }
      return obj
    })) || [];
    const legend = (props.isLengen && {legend: {data: (props.data.length && props.data.map(it => `${it.name}`)) || [], icon: 'circle'}}) || {};
    const option = {
      tooltip: {
        trigger: 'axis',
        formatter: (params) => {
          let str = `${params[0].axisValue}<br/>`
          params.forEach((it) => {
            str = str + it.marker + it.seriesName + ":" + it.value + (props.isPercentage ? '%' : '') + "<br/>"
          })
          return str
        }
      },
      ...legend,
      grid: {
        left: '5%',
        right: '8%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        splitLine: {     //网格线
          show: false
        },
        data: xlist
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: `{value}${props.isPercentage ? '%' : ''}`
        },
        splitLine :{    //网格线
          lineStyle:{
            type:'dashed'    //设置网格线类型 dotted：虚线   solid:实线
          },
          show:true //隐藏或显示
        }
      },
      series: serviesData
    };
    const renderedInstance = echarts.getInstanceByDom(barNode.current);
    if (renderedInstance) {
      myecharts = renderedInstance;
    } else {
      myecharts = echarts.init(barNode.current);
    }
    myecharts.setOption(option,true);  
  }
  return (
    <div ref={barNode}></div>
  )
}